package com.canbot.u05.activity.dance

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.alibaba.fastjson.JSON
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.canbot.u05.R
import com.canbot.u05.activity.BaseActivityNoTitle
import com.canbot.u05.activity.logd
import com.canbot.u05.activity.loge
import com.canbot.u05.bean.dance.Content
import com.canbot.u05.glide.GlideApp
import com.canbot.u05.socket.IpMsgConst
import kotlinx.android.synthetic.main.activity_dance_detail.*
import kotlinx.android.synthetic.main.activity_dance_detail.btn_back
import kotlinx.android.synthetic.main.activity_dance_manager.*
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import com.canbot.u05.activity.showToast
import com.canbot.u05.adapter.dance.MicListAdapter
import com.canbot.u05.bean.dance.ResponseInfo
import com.canbot.u05.bean.dance.VoiceWord
import com.canbot.u05.network.DanceUtil
import com.canbot.u05.socket.MsgSendUtils
import com.canbot.u05.socket.MsgType
import com.canbot.u05.utils.PathConst
import com.canbot.u05.view.DanceEditDialog
import com.canbot.u05.widget.LoadingDialogUtils


/**
 * 舞蹈详情页面
 */
class DanceDetailActivity : BaseActivityNoTitle() {
        private var adapter: MicListAdapter? = null
        private val newMics: MutableList<VoiceWord> = mutableListOf()
        private lateinit var context: Context
        private var oldImage:String? = null
        private var dialogLoading:Dialog? = null
        private val tipSound = listOf("wdxq_wdgj_u05_001.mp3","wdxq_wdgj_u05_002.mp3")
        override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
                context = this
                setContentView(R.layout.activity_dance_detail)
                val json = intent.getStringExtra("content")
                val content = JSON.parseObject(json, Content::class.java)
                initView(content)
                val random = (0..1).random()
                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.PAD_DANCE_TIP_PATH + tipSound[random])
        }

        private fun initView(content: Content) {

                dance_name.text = content.name
                dance_duration.text = "${content.duration}s"
                //dance_pic_default
                GlideApp.with(this)
                        .asDrawable()
                        .load(IpMsgConst.HTTP_URL_CHEST + content.defaultImage)
                        .thumbnail(0.1f)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                        .skipMemoryCache(false)
                        .placeholder(R.drawable.sales_banner01)//占位图
                        .error(R.drawable.ic_picture_loadfailed)
                        //.override(100, 100)
                        .into(dance_pic_default)
                if (!TextUtils.isEmpty(content.image)){
                        GlideApp.with(this)
                                .asDrawable()
                                .load(IpMsgConst.HTTP_URL_CHEST + content.image)
                                .thumbnail(0.1f)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                                .skipMemoryCache(false)
                                .placeholder(R.drawable.sales_banner01)//占位图
                                .error(R.drawable.ic_picture_loadfailed)
                                //.override(100, 100)
                                .into(dance_pic_custom)
                }

                if (content.showDefaultImage){
                        dance_pic_name_default.setTextColor(resources.getColor(R.color.dance_pic_title_default_ok,null))
                        dance_pic_name_custom.setTextColor(resources.getColor(R.color.dance_pic_title_default_no,null))
                }else{
                        dance_pic_name_default.setTextColor(resources.getColor(R.color.dance_pic_title_default_no,null))
                        dance_pic_name_custom.setTextColor(resources.getColor(R.color.dance_pic_title_default_ok,null))
                        oldImage = content.image
                }

                //设置声控命令列表
                val manager = LinearLayoutManager(this)
                manager.orientation = LinearLayoutManager.HORIZONTAL
                mic_list.layoutManager = manager
                val cmd = content.cmd + "|add"
                val mics = cmd.split("|")
                val micsTrim = mics.filter { !TextUtils.isEmpty(it.trim()) }
                micsTrim.forEach {
                        if (it.contains("&&")){
                                val split = it.split("&&")
                                if (split.size == 2){
                                        val commandName = split[0]
                                        val commandType = split[1]
                                        newMics.add(VoiceWord(commandName,commandType))
                                }
                        }else{
                                newMics.add(VoiceWord(it,content.type))
                        }

                }
                loge("声控命令词：" + newMics.size + ", " + cmd)
                if (newMics.size>5){
                        newMics.removeAt(newMics.size-1)
                }
                adapter = MicListAdapter(this, newMics)
                mic_list.adapter = adapter

                adapter?.addItemClickListener(object : MicListAdapter.OnItemClickListener {
                        override fun onItemClick(index: Int) {
                                //最好一个item点击添加其余item为修改
                                if (index == newMics.size - 1 && index < 5) {
                                        logd("点击增加命令词")
                                        if (newMics.size >5){
                                                showToast("触发指令不能超过5个")
                                                return
                                        }
                                        val danceEditDialog = DanceEditDialog(context)
                                        danceEditDialog.editDialog("", object : DanceEditDialog.OnSelectListener {
                                                override fun onCancle(view: View) {

                                                }

                                                override fun onEnsure(view: View, newName: String) {
                                                        logd("newMics:"+newMics)
                                                        newMics.add(newMics.size-1, VoiceWord(newName,"u"))
                                                        if (newMics.size==6){
                                                                newMics.removeAt(newMics.size-1)
                                                        }
                                                        adapter?.notifyDataSetChanged()
                                                        logd("newMics2:"+newMics)
                                                }

                                        }).show()

                                } else {
                                        loge("修改命令词:" + newMics[index])
                                        if (newMics[index].type.isEmpty()|| !newMics[index].type.equals("system")) {
                                                val danceEditDialog = DanceEditDialog(context)
                                                danceEditDialog.editDialog(newMics.get(index).name, object : DanceEditDialog.OnSelectListener {
                                                        override fun onCancle(view: View) {

                                                        }

                                                        override fun onEnsure(view: View, newName: String) {
                                                                newMics.set(index,VoiceWord(newName,"u"))
                                                                adapter?.notifyDataSetChanged()
                                                        }

                                                }).show()
                                        }else{
                                                showToast("系统舞蹈默认声控命令不能修改")
                                        }

                                }
                        }

                        override fun onItemLongClick(index: Int) {
                                //长按删除
                                loge("长按删除" + newMics[index])
                                if (newMics[index].type.isEmpty() || !newMics[index].type.equals("system")) {
                                        newMics.removeAt(index)
                                        if (!newMics.get(newMics.size-1).name.equals("add")){
                                                newMics.add(VoiceWord("add",""))
                                        }
                                }else{
                                        showToast("系统舞蹈默认声控命令不能删除")
                                }

                        }

                })

                btn_back.setOnClickListener {
                        finish()
                        overridePendingTransition(R.anim.face_zoom_enter,
                                R.anim.face_zoom_exit)
                }
                //提交数据
                btn_sure.setOnClickListener {
                        dialogLoading = LoadingDialogUtils.createLoadingDialog(this@DanceDetailActivity, resources.getString(R.string.request))
                        dialogLoading?.show()
                        if (!TextUtils.isEmpty(oldImage)){
                                content.image = oldImage as String
                                content.showDefaultImage = false
                        }
                        var mic:String = ""
                        if (newMics.size == 1){
                               newMics.clear()
                        }else{
                                newMics.forEach {
                                        if (it.type == "u"){
                                                mic+=it.name+"&&"+it.type+"|"
                                        }else{
                                                mic+=it.name+"|"
                                        }
                                }
                        }

                        content.cmd = mic.replace("add|","")
                        val cmd1 = content.cmd
                        loge("修改的cmd:$cmd1")
                        if ( cmd1.get(cmd1.length-1) == '|'){
                                content.cmd = cmd1.substring(0,cmd1.lastIndexOf("|"))
                        }
                        val json = JSON.toJSONString(content)
                        loge("确认修改舞蹈信息: "+json)

                        DanceUtil.updateDanceInfo(json,object :DanceUtil.DanceCallBack<ResponseInfo>{
                                override fun onSuccess(result: ResponseInfo) {
                                        dialogLoading?.dismiss()
                                        finish()
                                        overridePendingTransition(R.anim.face_zoom_enter,
                                                R.anim.face_zoom_exit)
                                }

                                override fun onFailure() {
                                        dialogLoading?.dismiss()
                                }
                        })
                }


                dance_pic_custom.setOnClickListener {
                        logd("选择舞蹈封面")
                        val intent = Intent(context,DanceChoosePicActivity::class.java)
                        startForResultActivity(intent,100)
                }

                btn_set_name.setOnClickListener {
                        logd("修改舞蹈名称")
                        val danceEditDialog = DanceEditDialog(context)
                        danceEditDialog.editDialog(content.name, object : DanceEditDialog.OnSelectListener {
                                override fun onCancle(view: View) {

                                }

                                override fun onEnsure(view: View, newName: String) {
                                        content.name = newName
                                        dance_name.text = newName
                                }

                        }).show()
                }

                rl_default_pic.setOnClickListener {
                        dance_pic_name_default.setTextColor(resources.getColor(R.color.dance_pic_title_default_ok,null))
                        dance_pic_name_custom.setTextColor(resources.getColor(R.color.dance_pic_title_default_no,null))
                        oldImage = null
                        content.showDefaultImage = true
                }
        }

        override fun onPause() {
                super.onPause()
                dialogLoading?.dismiss()
        }
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
                var image = data?.getStringExtra("image")
                logd("选择图片："+image)
                if(TextUtils.isEmpty(image) && TextUtils.isEmpty(oldImage)){
                        dance_pic_custom.setImageResource(R.drawable.dance_detail_add_pic_selector)
                        return
                }else if (TextUtils.isEmpty(image) && !TextUtils.isEmpty(oldImage)){
                        image = oldImage
                }
                dance_pic_name_default.setTextColor(resources.getColor(R.color.dance_pic_title_default_no,null))
                dance_pic_name_custom.setTextColor(resources.getColor(R.color.dance_pic_title_default_ok,null))
                GlideApp.with(this)
                        .asDrawable()
                        .load(IpMsgConst.HTTP_URL_CHEST + image)
                        .thumbnail(0.1f)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                        .skipMemoryCache(false)
                        .placeholder(R.drawable.sales_banner01)//占位图
                        .error(R.drawable.ic_picture_loadfailed)
                        //.override(100, 100)
                        .into(dance_pic_custom)
                oldImage = image
        }
}
